/**
 * 
 */
package com.thon.security;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

/**
 * @author thon
 *
 */
public class CaptchaFormAuthenticationFilter extends FormAuthenticationFilter {
	public static final String DEFAULT_CAPTCHA_PARAM = "captcha";

	private String captchaParam = DEFAULT_CAPTCHA_PARAM;

	public String getCaptchaParam() {

		return captchaParam;

	}

	protected String getCaptcha(ServletRequest request) {

		return WebUtils.getCleanParam(request, getCaptchaParam());

	}
	
	protected String getAuthcType(ServletRequest request) {

		return WebUtils.getCleanParam(request, "authcType");

	}

	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {

		String username = getUsername(request);
		String password = getPassword(request);
		String captcha = getCaptcha(request);
		String authcType = AuthcType.FORM;
		boolean rememberMe = isRememberMe(request);
		String host = getHost(request);
		
		if (StringUtils.isNotBlank(getAuthcType(request))&&getAuthcType(request).equals(AuthcType.SOCIAL)) {
			authcType = AuthcType.SOCIAL;
			return new CaptchaUsernamePasswordToken(username, "", rememberMe, host, captcha, authcType);
		}

		return new CaptchaUsernamePasswordToken(username, password, rememberMe, host, captcha, authcType);

	}
	
	 protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response)
	            throws Exception {
	        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
	        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
	         
	       // subject.getSession().setAttribute(SubjectUtil.CURRENT_USER, subject.getPrincipal());    //设置用户身份进session属性           
	         
	        String url = this.getSuccessUrl();
	        httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + url);    //页面跳转
	        return false;
	    }
}
